package com.hff.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hff.pojo.FileData;
import com.hff.service.FileService;
import com.hff.pojo.CallResult;
import com.hff.utils.FileUtil;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

    /*
    这是服务器端
     */
@RestController
@RequestMapping(value = "/file", method = {RequestMethod.POST, RequestMethod.GET})
public class FileController {

    @Resource
    private FileService fileServiceImpl;

    private static Logger logger = LoggerFactory.getLogger(FileController.class);

    @RequestMapping("upload")
    public  String fileUpload(@RequestParam("file") MultipartFile file) {
        InputStream in = null;
        OutputStream out = null;
        String uuid = UUID.randomUUID().toString();

        CallResult<String> result = new CallResult<String>(0, "OK", "上传成功");
        CallResult<String> resultNo = new CallResult<String>(410, "OK", "上传失败");

        try {
            in = new BufferedInputStream(file.getInputStream(), 16 * 1024);
            String originalFilename = file.getOriginalFilename();
            String path = "E:/TEST/";
            //ie上传文件该值是全路径，处理下
            if (originalFilename.indexOf("\\") > -1) {
                path = originalFilename.substring(originalFilename.indexOf("\\") + 1);
            }

            //获取文件的名称
            String filename = file.getOriginalFilename();

            FileData fileData = new FileData();
            //设置文件原始名字
            fileData.setFileName(filename);

            fileData.setId(uuid);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            String time = sdf.format(date);
            //设置创建时间
            fileData.setDate(time);
            //设置文件类型
            String b = filename.substring(filename.lastIndexOf(".") + 1);
            fileData.setFileClass(b);
            //设置文件大小
            fileData.setFileSize(file.getSize());
            String newName = uuid + "." + b;
            java.io.File files = new java.io.File(path, time);//记得地址末尾要加/;
            files.mkdir();
            //设置文件地址
//            path=request.getSession().getServletContext().getRealPath(time);
            path = path + time;
            fileData.setFileAddress(path);
            fileServiceImpl.saveFileData(fileData);
            String fileName = path + "/"+uuid+"."+b;

            out = new BufferedOutputStream(new FileOutputStream(fileName), 16 * 1024);
            byte[] buffer = new byte[16 * 1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            logger.info("upload返回结果：{}", result);
        } catch (Exception e) {
            logger.info("upload出错：{}", resultNo);
            e.printStackTrace();
        } finally {
            FileUtil.close(in);
            FileUtil.close(out);
        }
        return uuid;
    }


    @RequestMapping(value = "/download/{uuid}", method = RequestMethod.GET)
    public /*CallResult<String>*/ Integer download(HttpServletResponse response, @PathVariable("uuid") String uuid) throws IOException {

        FileData fileData = fileServiceImpl.queryFileData(uuid);
        String fileName = fileData.getFileName();
        String fileAddress = fileData.getFileAddress();
        String fileClass = fileData.getFileClass();


        try {
            InputStream inputStream = new FileInputStream(fileAddress + "/" + uuid + "." + fileClass);// 文件的存放路径
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
            logger.info("下载成功：{}", new CallResult<String>(0,"OK","下载成功"));
            return null;

        } catch (IOException e) {
            e.printStackTrace();
            logger.info("upload出错：{}", new CallResult<String>(410));
            return 410;
        }


    }


    @RequestMapping("/getFileData/{uuid}")
    public String getFileData(@PathVariable("uuid") String uuid) throws IOException {

        FileData fileData = fileServiceImpl.queryFileData(uuid);
        CallResult<String> result = new CallResult<String>(410, "NO", "上传失败");
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(fileData);
            logger.info("获取数据成功：{}", new CallResult<String>(0,"OK","获取数据成功"));
            return json;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            logger.info("get出错：{}", new CallResult<String>(410, "NO", "获取数据失败"));
            return null;
        }
    }


}
